package com.youlu.campus.service.job.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.EnterpriseJobInfo;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.VO.JobInfoDetailVO;
import com.youlu.campus.entity.VO.JobInfoVO;
import com.youlu.campus.entity.VO.req.FavoriteJboQueryVO;
import com.youlu.campus.service.integral.UserIntegralService;
import com.youlu.campus.service.job.JobInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class JobInfoServiceImpl implements JobInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserIntegralService userIntegralService;

    @Override
    public Page<ActivityUserJobInfo> favoriteJobList(FavoriteJboQueryVO req) {
        log.info(":>>> 开始获取收藏活动工作列表:{}", JSON.toJSONString(req));
        if (Objects.isNull(req)) {
            req = new FavoriteJboQueryVO();
            req.setPage(1);
            req.setPageSize(10);
        }
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getUserId())) {
            query.addCriteria(Criteria.where("userId").is(req.getUserId()));
        }
        if (Objects.nonNull(req.getFavorited())) {
            query.addCriteria(Criteria.where("favorited").is(req.getFavorited()));
        }
//        // 岗位类型
//        if (Objects.nonNull(req.getActivityJobInfoId())) {
//            query.addCriteria(Criteria.where("activityJobId").is(req.getActivityJobInfoId()));
//        }
        Long count = mongoTemplate.count(query, ActivityUserJobInfo.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ActivityUserJobInfo> infos = mongoTemplate.find(query.with(pageRequest), ActivityUserJobInfo.class);
        return PageableExecutionUtils.getPage(infos, pageRequest, () -> count);
    }

    @Override
    public Page<ActivityJobInfo> list(JobInfoVO request) {
        log.info(":>>> 开始获取活动工作列表:{}", JSON.toJSONString(request));
        if (Objects.isNull(request)) {
            request = new JobInfoVO();
            request.setPage(1);
            request.setPageSize(10);
        }
        List<String> jobIds = new ArrayList<>();
        Query query = new Query().addCriteria(Criteria.where("userId").is(request));
        List<ActivityUserJobInfo> infos = mongoTemplate.find(query, ActivityUserJobInfo.class);
        if (!CollectionUtils.isEmpty(infos)) {
            for (ActivityUserJobInfo u : infos) {
                if (StringUtils.isNotBlank(u.getActivityJobId())) {
                    jobIds.add(u.getActivityJobId());
                }
            }
        }
        Query query1 = new Query();
        if (!CollectionUtils.isEmpty(jobIds)) {
            query1.addCriteria(Criteria.where("id").nin(jobIds));
        }
//        if (StringUtils.isNotBlank(request.getType())) {
//            query1.addCriteria(Criteria.where("typeStr").is(request.getType()));
//        }
        // 岗位类型
        if (Objects.nonNull(request.getJobType())) {
            query1.addCriteria(Criteria.where("jobType").is(request.getJobType()));
        }
        // 是否收藏
        if (Objects.nonNull(request.getFavorited())) {
            query1.addCriteria(Criteria.where("favorited").is(request.getFavorited()));
        }
        Long count = mongoTemplate.count(query1, ActivityJobInfo.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        query.addCriteria(Criteria.where("deleted").ne(true));
        List<ActivityJobInfo> datas = mongoTemplate.find(query1.with(pageRequest), ActivityJobInfo.class);
        return PageableExecutionUtils.getPage(datas, pageRequest, () -> count);
    }

    @Override
    public Page<ActivityJobInfo> myJobs(JobInfoVO request) {

        log.info(":>>> 开始获取我参与的活动工作列表:{}", JSON.toJSONString(request));
        if (Objects.isNull(request)) {
            request = new JobInfoVO();
            request.setPage(1);
            request.setPageSize(10);
        }
        List<String> jobIds = new ArrayList<>();
        Query query = new Query().addCriteria(Criteria.where("userId").is(request));
        if (Objects.nonNull(request.getStatus())) {
            query.addCriteria(Criteria.where("status").is(request.getStatus()));
        }
        query.addCriteria(Criteria.where("joined").is(Boolean.TRUE));
        List<ActivityUserJobInfo> infos = mongoTemplate.find(query, ActivityUserJobInfo.class);
        if (!CollectionUtils.isEmpty(infos)) {
            for (ActivityUserJobInfo u : infos) {
                if (StringUtils.isNotBlank(u.getActivityJobId())) {
                    jobIds.add(u.getActivityJobId());
                }
            }
        }
        Query query1 = new Query();
        if (!CollectionUtils.isEmpty(jobIds)) {
            query1.addCriteria(Criteria.where("id").in(jobIds));
        }
        if (StringUtils.isNotBlank(request.getTypeStr())) {
            query1.addCriteria(Criteria.where("typeStr").is(request.getType()));
        }
        // 岗位类型
        if (Objects.nonNull(request.getJobType())) {
            query1.addCriteria(Criteria.where("jobType").is(request.getJobType()));
        }
        // 是否收藏
        if (Objects.nonNull(request.getFavorited())) {
            query1.addCriteria(Criteria.where("favorited").is(request.getFavorited()));
        }

        query1.addCriteria(Criteria.where("joined").ne(Boolean.FALSE));
        Long count = mongoTemplate.count(query1, ActivityJobInfo.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ActivityJobInfo> datas = mongoTemplate.find(query1.with(pageRequest), ActivityJobInfo.class);
        if (!CollectionUtils.isEmpty(datas)) {

            for (ActivityJobInfo a : datas) {
                Query q = new Query().addCriteria(Criteria.where("userId").is(request.getUserId()).and("activityJobId").is(a.getId()));
                ActivityUserJobInfo info = mongoTemplate.findOne(q, ActivityUserJobInfo.class);
                if (Objects.nonNull(info)) {
                    a.setJoined(info.getJoined());
                    a.setStatus(info.getStatus());
                    a.setAccomplishTime(info.getAccomplishTime());
                    a.setFavorited(info.getFavorited());
                    a.setFavoritedTime(info.getFavoritedTime());
                    a.setSignUpTime(info.getSignUpTime());
                }
            }
        }
        return PageableExecutionUtils.getPage(datas, pageRequest, () -> count);
    }

    @Override
    public JobInfoDetailVO getDetail(String userId, String id) {
        log.info(":>>> 开始获取工作详情:{},{}", userId, id);
        if (StringUtils.isBlank(id) || StringUtils.isBlank(userId)) {
            log.error(":>>> 获取工作详情错误,ID为空");
            throw new BusinessException("ID为空");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        ActivityJobInfo jobInfo = mongoTemplate.findOne(query, ActivityJobInfo.class);
        if (Objects.isNull(jobInfo)) {
            log.error(":>>> 工作详情错误错误,数据不存在");
            throw new BusinessException("数据不存在");
        }
        JobInfoDetailVO jobInfoDetailVO = new JobInfoDetailVO();
        BeanUtils.copyProperties(jobInfo, jobInfoDetailVO);
        if (StringUtils.isNotBlank(jobInfo.getEnterpriseInfoId())) {
            Query queryEnterprise = new Query();
            queryEnterprise.addCriteria(Criteria.where("id").is(jobInfo.getEnterpriseInfoId()));
            EnterpriseInfo enterpriseInfo = mongoTemplate.findOne(queryEnterprise, EnterpriseInfo.class);
            if (Objects.nonNull(enterpriseInfo)) {
                jobInfoDetailVO.setEnterpriseInfo(enterpriseInfo);
            }
        }
        /**
         * 是否收藏
         */
        Query queryFavo = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityJobId").is(id));
        ActivityUserJobInfo a = mongoTemplate.findOne(queryFavo, ActivityUserJobInfo.class);
        if (Objects.isNull(a)) {
            jobInfoDetailVO.setMyFavorities(false);
            jobInfoDetailVO.setJoined(false);
        } else {
            if (Boolean.TRUE.equals(a.getFavorited())) {
                jobInfoDetailVO.setMyFavorities(true);
            } else {
                jobInfoDetailVO.setMyFavorities(false);
            }
        }
        Query queryRec = new Query();
        queryRec.addCriteria(Criteria.where("type").is(jobInfo.getType()));
        queryRec.addCriteria(Criteria.where("jobType").is(jobInfo.getJobType()));
        queryRec.addCriteria(Criteria.where("id").ne(jobInfo.getId()));
        queryRec.limit(5);
        List<ActivityJobInfo> jobInfos = mongoTemplate.find(queryRec, ActivityJobInfo.class);
        jobInfoDetailVO.setCorrelateRecommend(jobInfos);
        jobInfoDetailVO.setWorkingAddress(jobInfo.getWorkingAddress());
        jobInfoDetailVO.setWorkingRe(jobInfo.getWorkingRe());
        jobInfoDetailVO.setWorkingTime(jobInfo.getWorkingTime());
        jobInfoDetailVO.setWorkingDay(jobInfo.getWorkingDay());
        log.info(":>>> 用户:{}, 的工作详情为:{}", JSON.toJSONString(jobInfoDetailVO));
        return jobInfoDetailVO;
    }

    @Override
    public boolean favoriteJob(String userId, String activityJobId) {
        log.info(":>>> 用户:{} 开始收藏工作:{},", userId, activityJobId);
        if (StringUtils.isBlank(activityJobId) || StringUtils.isBlank(userId)) {
            log.error(":>>> 参数错误:用户ID或工作ID为空");
            throw new BusinessException("参数错误:用户ID或工作ID为空");
        }
        Date date = new Date();
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(activityJobId));
        ActivityJobInfo jobInfo = mongoTemplate.findOne(query, ActivityJobInfo.class);
        if (Objects.isNull(jobInfo)) {
            log.error(":>>> 工作:{} 数据不存在", activityJobId);
            throw new BusinessException("工作数据不存在");
        }
        Query queryFavo = new Query();
        queryFavo.addCriteria(Criteria.where("userId").is(userId));
        queryFavo.addCriteria(Criteria.where("activityJobId").is(activityJobId));
        ActivityUserJobInfo exist = mongoTemplate.findOne(queryFavo, ActivityUserJobInfo.class);
        if (Objects.nonNull(exist)) {
            log.info(":>>> 用户:{} 已经收藏该工作:{}", userId, activityJobId);
            if (Boolean.TRUE.equals(exist.getFavorited())) {
                log.info(":>>> 用户:{} 已经收藏该工作:{}", userId, activityJobId);
                return true;
            }
            exist.setFavorited(true);
            exist.setFavoritedTime(date);
            exist.setUpdatedTime(date);
            exist.setActivityJobInfo(jobInfo);
            mongoTemplate.save(exist);
            return true;
        }
        exist = new ActivityUserJobInfo();
        exist.setUserId(userId);
        exist.setActivityJobId(activityJobId);
        exist.setFavorited(true);
        exist.setFavoritedTime(date);
        exist.setUpdatedTime(date);
        exist.setStatus(0);
        exist.setCreatedTime(date);
        exist.setActivityJobInfo(jobInfo);
        mongoTemplate.insert(exist);
        return true;
    }

    @Override
    public boolean unFavoriteJob(String userId, String activityJobId) {
        log.info(":>>> 用户:{} 开始取消收藏工作:{},", userId, activityJobId);
        if (StringUtils.isBlank(activityJobId) || StringUtils.isBlank(userId)) {
            log.error(":>>> 参数错误:用户ID或工作ID为空");
            throw new BusinessException("参数错误:用户ID或工作ID为空");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(activityJobId));
        ActivityJobInfo jobInfo = mongoTemplate.findOne(query, ActivityJobInfo.class);
        if (Objects.isNull(jobInfo)) {
            log.error(":>>> 工作:{} 数据不存在", activityJobId);
            throw new BusinessException("工作数据不存在");
        }
        Date date = new Date();
        Query queryFavo = new Query();
        queryFavo.addCriteria(Criteria.where("userId").is(userId));
        queryFavo.addCriteria(Criteria.where("activityJobId").is(activityJobId));
        ActivityUserJobInfo exist = mongoTemplate.findOne(queryFavo, ActivityUserJobInfo.class);
        if (Objects.nonNull(exist)) {
            log.info(":>>> 用户:{} 已经收藏该工作:{}", userId, activityJobId);
            if (Boolean.FALSE.equals(exist.getFavorited())) {
                log.info(":>>> 用户:{} 已经取消收藏该工作:{}", userId, activityJobId);
                return true;
            }
            exist.setFavorited(false);
            exist.setFavoritedTime(null);
            exist.setUpdatedTime(date);
            mongoTemplate.save(exist);
            return true;
        }
        return true;
    }

    @Override
    public boolean joinJob(ActivityUserJobInfo jobInfo, String userId) {
        log.info(":>>> 用户:{} 开始参与工作:{}", userId, JSON.toJSONString(jobInfo));
        if (Objects.isNull(jobInfo) || StringUtils.isBlank(jobInfo.getActivityJobId())
                || StringUtils.isBlank(jobInfo.getName())
                || StringUtils.isBlank(jobInfo.getMobile()) || StringUtils.isBlank(jobInfo.getEmail())) {
            log.error(":>>> 参数错误:{},报名工作");
            throw new BusinessException("报名工作参数错误");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(jobInfo.getActivityJobId()));
        ActivityJobInfo jobInfoDb = mongoTemplate.findOne(query, ActivityJobInfo.class);
        if (Objects.isNull(jobInfoDb)) {
            log.error(":>>> 工作:{} 数据不存在", jobInfo.getActivityJobId());
            throw new BusinessException("工作数据不存在");
        }
        Query queryUserJob = new Query();
        queryUserJob.addCriteria(Criteria.where("userId").is(userId));
        queryUserJob.addCriteria(Criteria.where("activityJobId").is(jobInfo.getActivityJobId()));
        ActivityUserJobInfo activityUserJobInfo = mongoTemplate.findOne(queryUserJob, ActivityUserJobInfo.class);
        if (Objects.nonNull(activityUserJobInfo)) {
            log.error(":>>> 用户:{} 已经参与工作:{}", userId, jobInfo.getActivityJobId());
            activityUserJobInfo.setSignUpTime(new Date());
            // 进行中
            activityUserJobInfo.setStatus(1);
            activityUserJobInfo.setSignUpTime(new Date());
            activityUserJobInfo.setJoined(true);
            activityUserJobInfo.setActivityJobInfo(jobInfoDb);
            activityUserJobInfo.setName(jobInfo.getName());
            activityUserJobInfo.setMobile(jobInfo.getMobile());
            activityUserJobInfo.setEmail(jobInfo.getId());
            activityUserJobInfo.setUniversityId(jobInfo.getUniversityId());
            mongoTemplate.save(activityUserJobInfo);
            return true;
        }
        activityUserJobInfo = new ActivityUserJobInfo();
        activityUserJobInfo.setActivityJobId(jobInfo.getId());
        activityUserJobInfo.setCreatedTime(new Date());
        activityUserJobInfo.setUserId(userId);
        // 进行中
        activityUserJobInfo.setStatus(1);
        activityUserJobInfo.setSignUpTime(new Date());
        activityUserJobInfo.setActivityJobInfo(jobInfoDb);
        activityUserJobInfo.setName(jobInfo.getName());
        activityUserJobInfo.setMobile(jobInfo.getMobile());
        activityUserJobInfo.setEmail(jobInfo.getId());
        activityUserJobInfo.setFavorited(false);
        activityUserJobInfo.setJoined(true);
        activityUserJobInfo.setEmail(jobInfo.getEmail());
        activityUserJobInfo.setUniversityId(jobInfo.getUniversityId());
        mongoTemplate.insert(activityUserJobInfo);
        UserIntegralPO userIntegralPO=new UserIntegralPO();
        userIntegralPO.setUserId(userId);
        // 签到1积分
        userIntegralPO.setIntegral(5);
        userIntegralPO.setDesc("签到实习/兼职获得5个国青豆");
        userIntegralPO.setBizId(jobInfo.getId());
        userIntegralPO.setBizType("job");
        userIntegralService.addIntegral(userIntegralPO);
        UserPO userPO = new UserPO();
        userPO.setId(userId);
        userPO.setEmail(jobInfo.getEmail());
        userPO.setMobile(jobInfo.getMobile());
        userPO.setName(jobInfo.getName());
        if (StringUtils.isNotBlank(jobInfo.getUniversityId())) {
            userPO.setUniversityId(jobInfo.getUniversityId());
        }
        mongoTemplate.save(userPO);
        return true;
    }

    @Override
    public EnterpriseJobInfo getEnterpriseJobInfo(String id) {
        log.info(":>>> 开始获取企业信息:{}", id);
        if (StringUtils.isBlank(id)) {
            log.error(":>>> 企业信息ID为空");
            throw new BusinessException("参数错误:ID为空");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        EnterpriseInfo enterpriseInfo = mongoTemplate.findOne(query, EnterpriseInfo.class);
        if (Objects.isNull(enterpriseInfo)) {
            log.error(":>>> 企业:{} 信息不存在", id);
            throw new BusinessException("企业信息不存在");
        }
        EnterpriseJobInfo enterpriseJobInfo = new EnterpriseJobInfo();
        enterpriseJobInfo.setEnterpriseInfo(enterpriseInfo);

        Query queryUserJob = new Query();
        queryUserJob.addCriteria(Criteria.where("activityJobId").is(id));
        queryUserJob.limit(5);
        List<ActivityUserJobInfo> activityUserJobInfos = mongoTemplate.find(queryUserJob, ActivityUserJobInfo.class);
        enterpriseJobInfo.setJobInfos(activityUserJobInfos);
        return enterpriseJobInfo;
    }

    @Override
    public List<ActivityUserJobInfo> getActivityUserJobInfoByUserId(String userId, List<Integer> statuses) {
        log.info(":>>> 开始获取用户参与工作信息:{},{}", userId, JSON.toJSONString(statuses));
        if (StringUtils.isBlank(userId) || CollectionUtils.isEmpty(statuses)) {
            log.error(":>>> 用户参与工作信息参数错误:用户ID或状态为空");
            throw new BusinessException("用户参与工作信息参数错误:用户ID或状态为空");
        }
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("status").in(statuses));
        List<ActivityUserJobInfo> datas = mongoTemplate.find(query, ActivityUserJobInfo.class);
        return datas;
    }

    @Override
    public Integer getPartTimeJobDuration(String userId) {
        log.info(":>>> 开始获取用户:{} 兼职时长", userId);
        if (StringUtils.isBlank(userId)) {
            log.error(":>>> 开始获取用户兼职时长错误:用户ID为空");
            throw new BusinessException("获取用户兼职时长错误:用户ID为空");
        }
        List<Integer> statuses = new ArrayList<>();
        // 完成
        statuses.add(2);
        List<ActivityUserJobInfo> datas = this.getActivityUserJobInfoByUserId(userId, statuses);
        if (CollectionUtils.isEmpty(datas)) {
            return 0;
        }
        Integer duration = 0;
        for (ActivityUserJobInfo activityUserJobInfo : datas) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(activityUserJobInfo.getActivityJobId()));
            ActivityJobInfo job = mongoTemplate.findOne(query, ActivityJobInfo.class);
            if (Objects.nonNull(job) && Objects.nonNull(job.getDuration())) {
                duration = duration + job.getDuration();
            }

        }
        log.info(":>>> 用户:{} 的工作时长为:{}", userId, duration);
        return duration;
    }
}
